package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version V1.11
 * @ClassName:
 * @Description:
 * @Date
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/toList")
    public String toList(){
        return "list";
    }

    // @RequestMapping(value = "/add",method = RequestMethod.POST)
    @GetMapping("/toUserAdd")
    public String toAdd(){
        return "userAdd";
    }

    @PostMapping("/add")
    public String add(HttpServletRequest request, Model model, @Valid SysUser sysUser, BindingResult bindingResult, MultipartFile idpic) throws IOException{


        if (bindingResult.hasErrors()) {
            //获取所有的错误
            List<FieldError> fieldError =bindingResult.getFieldErrors();
            for (FieldError fieldErrors:fieldError) {
                model.addAttribute(fieldErrors.getField()+"Error",fieldErrors.getDefaultMessage());

            }
            return "userAdd";
        }
        // 指定文件存储的目录
        String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "upload";  // ?
        //自定义文件名
        String suffix = idpic.getOriginalFilename().substring(idpic.getOriginalFilename().lastIndexOf("."));
        String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;
        File fileTo = new File(path + File.separator + fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()) {
            fileTo.mkdirs();
        }
        //核心代码： 将文件存储到指定位置
        idpic.transferTo(fileTo);

        sysUser.setIdpicpath(fileName);

        int result= sysUserService.add(sysUser);
        if (result>0) {
            return "redirect:toList";
        }
        model.addAttribute("errorMsg","新增失败");
        return "userAdd";
    }

    @GetMapping("/view/{userId}")
    public String view(Model model,@PathVariable("userId") Integer id){
        SysUser sysUser = sysUserService.selectId(id);
        model.addAttribute("sysUser",sysUser);
        return "userView";
    }

    @GetMapping(value = "/view2/{userId}",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String view2(@PathVariable("userId") Integer id){
        SysUser sysUser = sysUserService.selectId(id);
        String json=  JSON.toJSONString(sysUser);
        return json;
    }

    @GetMapping("/toEdit/{id}")
    public String toEdit(Model model,@PathVariable Integer id){
        SysUser sysUser = sysUserService.selectId(id);

        model.addAttribute("sysUser",sysUser);
        return "userEdit";
    }

    @PostMapping(value = "/edit")
    public String edit(HttpServletRequest request, Model model,@Valid SysUser sysUser, BindingResult bindingResult, MultipartFile idpic) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "upload";  // ?
        //自定义文件名
        String suffix = idpic.getOriginalFilename().substring(idpic.getOriginalFilename().lastIndexOf("."));
        String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;
        File fileTo = new File(path + File.separator + fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()) {
            fileTo.mkdirs();
        }
        //核心代码： 将文件存储到指定位置
        idpic.transferTo(fileTo);

        sysUser.setIdpicpath(fileName);
        int result=sysUserService.edit(sysUser);
        return "redirect:toList";
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(Model model,@PathVariable Integer id){
        int result=sysUserService.del(id);
        return result>0?"1":"0";
    }

    @GetMapping("accountExists")
    @ResponseBody
    public String accountExists(String account){
        int i = sysUserService.selectByAccount(account);
        return i>0? "1":"0";
    }

    // @RequestMapping(value = "/list",method = RequestMethod.GET)
    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Model model, Integer page, Integer limit,String realName,Integer roleId) throws IOException {

        List<SysUser> userList = sysUserService.list(page, limit,realName,roleId);
        /*
         *  {"code":0,"count":1000,"data":[userList],"msg":""}
         */
        int count = sysUserService.count(realName, roleId);
        TableVO tableVO = new TableVO(0, count, userList, "");

        String json = JSON.toJSONString(tableVO);

        // response.setContentType("application/json;charset=utf-8");
        // response.getWriter().print(json);

        return json;
    }


    @GetMapping("/list2")
    public String list2(Map<String,Object> map, @RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(this);
        map.put("id",id);
        return "forward:toList";
    }

    @GetMapping("/list1")
    public ModelAndView list1(@RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("list.jsp");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

}